package login

import (
	"AI/sql/disposition"
	status "AI/util"
	"crypto/md5"
	"database/sql"
	"encoding/base64"
	"encoding/hex"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
)

func main() {
}

type MysqlApi struct {
	UserName string   // 数据库登录用户名
	Password string   // 数据库登录密码
	Host     string   // 数据库登录地址
	Port     int      // 数据库端口
	DbName   string   // 数据库名称
	Charset  string   // 字符编码
	Db       *sqlx.DB // 数据库实例
}
type info struct {
	id          string
	username    string
	Account     string
	creatTime   string
	status      int
	token       string
	phoneNumber string
}

func MysqlConfig() *MysqlApi {
	Login := new(MysqlApi)
	Login.Charset = "utf8"         // 字符编码
	Login.UserName = "root"        // 登录用户
	Login.Port = 3306              // 数据库端口
	Login.Host = "127.0.0.1"       // 数据库登录地址
	Login.Password = "mwx17620351" // 数据库登录密码
	Login.DbName = "liumou"        // 数据库名称
	Arg := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", Login.UserName, Login.Password, Login.Host, Login.Port, Login.DbName, Login.Charset)
	fmt.Println(Arg)
	Db, err := sqlx.Open("mysql", Arg)
	if err != nil {
	}
	Login.Db = Db
	return Login

}

func PasOrAccount(Data map[string]string, c *gin.Context) {
	Account, isAccount := Data["Account"]
	pws, ispws := Data["pws"]
	if !isAccount || !ispws {
		c.JSON(http.StatusOK, gin.H{
			"code": status.Dataerrors,
			"msg":  "账号或者密码错误,请重新输入",
		})
		return
	} else {
		// 连接数据库
		db, err := sql.Open(disposition.Usersql["sqlname"], disposition.Usersql["sqlurl"])
		if err != nil {
			panic(err)
		}

		sql := fmt.Sprintf(`select id,username,Account,status,token,phoneNumber,creatTime from userinfo where Account = "%s" and paswrod = "%s"`, Account, pws)
		rows, err := db.Query(sql)

		fmt.Println(err)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": status.Dataerrors,
				"msg":  "账号或者密码错误,请重新输入",
			})
		}

		if err := db.Ping(); err != nil {
			fmt.Println("连接失败")
			panic(err)
		}
		if err != nil {
			panic(err.Error())
		}
		for rows.Next() {
			var userinfo info
			err = rows.Scan(&userinfo.id, &userinfo.username, &userinfo.Account, &userinfo.status, &userinfo.token, &userinfo.phoneNumber, &userinfo.creatTime)
			fmt.Println(userinfo.status)
			if userinfo.status == 0 {
				c.Abort()
				c.JSON(http.StatusOK, gin.H{
					"code": status.Illegal,
					"msg":  "该账号已被封禁",
					"data": "",
				})
				return

			}
			resolveinfo := map[string]interface{}{"username": userinfo.username, "Account": userinfo.Account, "phoneNumber": userinfo.phoneNumber, "creatTime": userinfo.creatTime, "status": userinfo.status, "token": userinfo.token}
			//修改token
			resolveinfo["token"] = SetToken(db, c, resolveinfo)
			// 存入数据库
			sqls := fmt.Sprintf(`UPDATE userinfo SET token = "%s" where Account = "%s" and paswrod = "%s"`, resolveinfo["token"], Account, pws)

			db.Exec(sqls)

			c.JSON(http.StatusOK, gin.H{
				"code": status.Success,
				"msg":  "登录成功",
				"data": resolveinfo,
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": status.Dataerrors,
			"msg":  "账号或者密码错误,请重新输入",
		})
		defer db.Close()
	}

}

func VerifyAccount() {
	fmt.Println(123)
}
func SetToken(db *sql.DB, c *gin.Context, resolveinfo map[string]interface{}) string {
	// 获取当前时间
	timeStampN := strconv.FormatInt(time.Now().UnixNano(), 10) //纳秒为单位的时间戳
	fmt.Print(timeStampN, "\n")
	// 获取用户名
	fmt.Print(resolveinfo["Account"], "\n")
	// 获取注册时间
	fmt.Print(resolveinfo["creatTime"], 123456, "\n")

	// 然后变成string
	s := fmt.Sprintf("%s-%s-%s", resolveinfo["creatTime"], resolveinfo["Account"], timeStampN)
	// 获取到token 转成md5 然后转成base64
	d := []byte(s)
	m := md5.New()
	m.Write(d)
	return base64.StdEncoding.EncodeToString([]byte(hex.EncodeToString(m.Sum(nil))))
}
